package com.tude.egarticle3.base.exception;


import com.tude.egarticle3.base.response.CodeMsg;
import com.tude.egarticle3.base.response.JsonResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandel {

    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String data = e.getFieldError().getDefaultMessage();
        return new JsonResult(CodeMsg.VALIDATED_ERROR, data);
    }

    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e) {
        String data = e.getMessage().split(":")[1].trim();
        return new JsonResult(CodeMsg.VALIDATED_ERROR, data);
    }
}
